﻿using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Quartz;
using Choucius.Boilerplate9.DtoBase.MES;
using Choucius.Boilerplate9.OutboundTasks;
using Choucius.Boilerplate9.ProductionLines;
using Choucius.Boilerplate9.UR5208;
using Microsoft.Extensions.Logging;
using Quartz;
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Choucius.Boilerplate9.JobServices
{
    public class DataPolling : JobBase, ITransientDependency
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger<DataPolling> _logger;
        private readonly IOutboundTaskAppService _outboundTaskAppService;

        public DataPolling(IHttpClientFactory httpClientFactory, ILogger<DataPolling> logger, IOutboundTaskAppService outboundTaskAppService)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
            _outboundTaskAppService = outboundTaskAppService;
        }

        //public DataPolling(IRepository<ProductionLine, Guid> productionLineRepository, IUR5208AppService ur5208AppService)
        //{
        //    _productionLineRepository = productionLineRepository;
        //    _ur5208AppService = ur5208AppService;
        //}

        public override Task Execute(IJobExecutionContext context)
        {
            Task t = Task.Run(async () =>
            {
                using (var cmd = UnitOfWorkManager.Begin(System.Transactions.TransactionScopeOption.RequiresNew))
                {
                    //_ = _ur5208AppService.UR5208ReadAndSaveAsync("192.168.4.51", 6000);

                    //***********相关业务代码***************
                    // 调用MES接口
                    //var result = await _mesApiClient.PostAsync("http://192.168.9.88:9002/Frame/SqlData?cmdname=selectZSPlan", "");
                    string url = "http://192.168.9.88:9002/Frame/SqlData?cmdname=selectZSPlan";
                    string responseBody = string.Empty;
                    using (var httpClient = _httpClientFactory.CreateClient())
                    {
                        var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
                        var response = await httpClient.PostAsync(url, content);
                        if (response.IsSuccessStatusCode)
                        {
                            responseBody = await response.Content.ReadAsStringAsync();
                            _logger.LogInformation(responseBody);
                        }
                        else if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                        {
                            _logger.LogError($"{response.StatusCode}: Resource not found.");
                        }
                        else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
                        {
                            _logger.LogError($"{response.StatusCode}: Internal server error.");
                        }
                        else
                        {
                            // 你可以根据需要添加更多的状态码检查
                            _logger.LogError(response.StatusCode.ToString());
                        }
                        //response.EnsureSuccessStatusCode();
                    }
                    if (!string.IsNullOrEmpty(responseBody))
                    {
                        // 反序列化Json
                        MesDto dto = JsonSerializer.Deserialize<MesDto>(responseBody);
                        // TODO: 创建明日出库任务
                        _ = _outboundTaskAppService.CreateOutboundTaskFromMesAsync(dto.data.ds);
                    }

                    await cmd.CompleteAsync();
                }
                //Console.WriteLine(DateTime.Now); 
            });
            return t;
        }
    }
}
